package com.example.activity.controller;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    /*管理流程定义*/
    private RepositoryService repositoryService;
    @Autowired
    /*执行管理、包括启动、推进、删除流程实例等操作*/
    private RuntimeService runtimeService;
    @Autowired
    /*任务管理*/
    private TaskService taskService;

    @RequestMapping("/firstDemo")
    public Map firstDemo() {
        Map result = new HashMap();
        //根据bpmn文件部署流程
        Deployment deployment = repositoryService.createDeployment().addClasspathResource("demo.bpmn").deploy();
        //获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
        //启动流程定义，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceById(processDefinition.getId());
        String processId = pi.getId();
        System.out.println("流程创建成功，当前流程实例ID："+processId);
        result.put("流程创建成功，当前流程实例ID" , processId);

        Task task=taskService.createTaskQuery().processInstanceId(processId).singleResult();
        System.out.println("第一次执行前，任务名称："+task.getName());
        result.put("第一次执行前，任务名称" , task.getName());
        taskService.complete(task.getId());

        task = taskService.createTaskQuery().processInstanceId(processId).singleResult();
        System.out.println("第二次执行前，任务名称："+task.getName());
        result.put("第二次执行前，任务名称" , task.getName());
        taskService.complete(task.getId());

        task = taskService.createTaskQuery().processInstanceId(processId).singleResult();
        System.out.println("任务执行完毕，流程实例ID："+processId);
        result.put("任务执行完毕，流程实例ID" , processId);
        result.put("任务执行完毕，部署ID" , deployment.getId());
        return result;
    }
}
